// import { getPrepay } from "../../utils/pay/wxpay";
import { prepayJsapi, reSign } from "../../utils/pay/wxpay-partner";
import { api } from "./api";
import { fillShopName, getShopInfo } from "./shop";

let noOrdUids = [];
let noOrdData = null;
export function onOrderChange(body) {
  const { userId } = body.row || body;
  const idx = noOrdUids.indexOf(userId);
  console.log("order-change", userId, idx);
  if (idx > -1) {
    noOrdUids.splice(idx, 1);
  }
}

export async function getOrders(body, userId) {
  if (noOrdUids.includes(userId)) {
    return noOrdData;
  }
  body._data = 1;
  body.userId = userId;
  const data = await api.getOrderList(body);

  if (data.count) {
    await fillShopName(data.rows);
  } else if (body.status === undefined && body._page == 1) {
    noOrdUids.push(userId);
    if (!noOrdData) noOrdData = data;
  }
  return data;
}

export async function prepayOrder(body, reqUser, ip, notify_url) {
  let order_no;
  let ordId;
  let payment;
  if (body.id > 0) {
    const ordRow = await api.getOrder(body.id);
    if (!ordRow) throw "订单ID不存在";
    if (ordRow.userId != reqUser.id) throw "用户信息不一致";
    order_no = ordRow.order_no;
    ordId = ordRow.id;
    body = ordRow;
    const reusePay = Date.now() - ordRow.updatedAt < 3600e3; // payment: 2小时有效
    if (!ordRow.paid && ordRow.pay_info && reusePay) {
      payment = ordRow.pay_info;
      reSign(payment);
    }
  } else if (!body.buy_id || !body.count || !body.total_price) {
    throw "缺少参数";
  }
  // 检查商品
  const item = await api.getGoodsRow(body.buy_id);
  if (!item) {
    throw "商品不存在";
  }
  const total_price = (item.price * body.count).toFixed(2);
  if (body.total_price != total_price) {
    throw "价格不一致，请重新进入下单";
  }
  const restAmount = item.amount - item.sell_num;
  if (body.count > restAmount) {
    throw "商品库存不足";
  }
  // 检查门店
  const shop = await api.getShopRow(item.sid);
  if (!shop || !shop.on) {
    throw "门店已下架";
  }
  if (!shop.mch_id) {
    throw "门店未设置商户号";
  }
  // 检查用户
  const isAgent = !!body.mobile;
  if (isAgent && reqUser.sid != shop.id) {
    throw "无门店权限";
  }
  const user = await api.getUserInfoBase(
    isAgent
      ? {
          mobile: body.mobile,
        }
      : {
          id: reqUser.id,
        }
  );
  if (!user || !user.openid) {
    throw "用户信息不存在";
  }
  // 下单
  if (!body.id) {
    const rand = (Math.random() + "").substring(2, 6);
    order_no = new Date().format("yymmddHHiiss") + rand;
    const ordBody = {
      sid: item.sid,
      order_no,
      buy_id: item.id,
      buy_info: {
        name: item.name,
        img: item.img,
        price: item.price,
        times: item.times,
        mins: item.mins,
        days: item.days,
      },
      total_price,
      count: body.count,
      total_times: body.count * item.times,
      userId: user.id,
      status: isAgent ? 1 : 0,
      mobile: body.mobile,
    };
    const { id } = await api.postOrder(ordBody);
    ordId = id;
  }
  if (isAgent) {
    api.postActLog({
      path: "prepay",
      act: "agent",
      extra: {
        ordId,
        mobile: body.mobile,
      },
      userId: reqUser.id,
      ip,
    });
  }
  // 生成支付信息
  if (!payment && !isAgent) {
    const params = {
      description: "真冰乐园-" + item.name + " × " + body.count,
      out_trade_no: order_no,
      amount: {
        total: total_price * 100,
      },
      settle_info: {
        profit_sharing: true,
      },
      payer: {
        // sp_openid: user.openid,
      },
      notify_url,
      scene_info: {
        payer_client_ip: ip,
        device_id: user.id + "",
      },
    };
    params.sub_mchid = shop.mch_id;
    // params.sub_mchid = "1681798615"; //和风益鸣科技下的爱希体育（爱运动）
    // params.sub_mchid = "1681894250"; // 爱希体育下的青云体育
    // params.sub_appid = "wx5f28eb64f43e00ac"; // 部署在子商户的小程序
    params.payer[params.sub_appid ? "sub_openid" : "sp_openid"] = user.openid;
    payment = await prepayJsapi(params);
    await api.postOrder({
      id: ordId,
      pay_info: {
        ...payment,
        paySign: null,
      },
    });
  }
  return {
    payment,
    order_no,
  };
}

export async function afterPay(order_no) {
  const row = await api.getOrder({
    order_no,
  });
  if (!row) throw "订单不存在";
  if (row.status == 0) {
    await api.postOrder({
      id: row.id,
      status: -1, // 支付中
    });
  }
  return {
    id: row.id,
    paid: row.paid,
  };
}

export async function getOrderInfo(body, user) {
  if (!body.id && !body.order_no) {
    throw "缺少参数";
  }
  const data = await api.getOrder(
    body.id || {
      order_no: body.order_no,
    }
  );
  if (!data) {
    throw "订单ID不存在";
  }
  const isAdm = user.sid == data.sid || user.role == 1;
  if (body.order_no && !isAdm) {
    throw "无此店铺权限";
  }
  if (data.used_times) {
    data.logs = await api.getOrderLogs({
      oid: data.id,
      _limit: Math.max(10, data.used_times),
    });
  }
  if (isAdm) {
    data.user = await api.getUserInfo({
      _attributes: ["faceImg", "mobile", "id"],
      id: data.userId,
    });
  }
  data.shop_info = await getShopInfo(data.sid);
  return data;
}
